package com.example.administrator.myview.util;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * 封装起来的viewHolder
 */
public class ViewHolder {
	
	private final SparseArray<View> mViews;
	private View mConvertView;
	
	public ViewHolder(Context context, ViewGroup parent, int layoutId){
		this.mViews = new SparseArray<>();
		mConvertView =LayoutInflater.from(context).inflate(layoutId, parent, false);
		//setTag
		mConvertView.setTag(this);
	}
	
	/**
	 * 获取一个viewHolder对象
	 */
	public static ViewHolder get(Context context,View convertView,ViewGroup parent,int layoutId){
		if(convertView ==null){
			return  new ViewHolder(context, parent, layoutId);
		}
		return (ViewHolder)convertView.getTag();
	}
	/**
	 * 通过控件的Id获取，如果没有则加入Views
	 */
	public <T extends View> T getView(int ViewId){
		View view =mViews.get(ViewId);
		if(view == null){
			view =mConvertView.findViewById(ViewId);
			mViews.put(ViewId, view);
		}
		return (T)view;
	}
	
	public View getConvertView(){
		return mConvertView;
	}

}
